var express = require('express');
var router = express.Router();
var db = require("ykt-mongo")

// jsonwebtoken express-jwt
let jwt=require("jsonwebtoken")

/* GET users listing. */
router.get('/', function(req, res, next) {
	res.send('respond with a resource');
});

// 注册
router.post("/register", function(req, res, next) {

	//接收前端传过来的账号密码
	console.log(req.body);
	let userData = req.body;
	console.log("userData", userData);

	db.collection("users").insert(userData, function(data) {
		console.log("添加的结果", data);
		if (data.result.ok == 1 && data.result.n == 1) {
			res.send({
				code: 0,
				msg: "注册成功"
			})
		} else {
			res.send({
				code: 1,
				msg: "注册失败"
			})
		}
	})

})


//登录接口
router.post("/login", function(req, res, next) {
	//拿到前端传过来的账号跟密码
	let userData = req.body;
	console.log('需要登录的账号密码', userData);


	db.collection("users").find(userData, function(data) {
		console.log("查询到的结果", data);
		if (data.length > 0) {
			let token=jwt.sign(userData,"yang",{
				expiresIn:60*60*24
			})
			res.send({
				token,
				code: 0,
				msg: "登录成功"
			})
		} else {
			res.send({
                code:1,
				msg:"账号密码错误，请重新输入"
			})
		}
	})
})


module.exports = router;
